import React, { Component } from 'react'
import './index.less'
import { Row, Col, DatePicker, Table, Modal, Button, message } from 'antd'
import WeeklyForm1 from './weekForm1'
import WeeklyForm2 from './weekForm2'
import WeeklyForm3 from './weekForm3'
import WeeklyForm4 from './weekForm4'
import moment from 'moment'
import Http from '../../../../axios'
const { RangePicker } = DatePicker;

export default class TeamWeekly extends Component {

  state = {
    userInfo: '',
    date: '',
    index1: 1,
    index2: 1,
    index3: 1,
    index4: 1,
    data1: [],
    modalVisible1: false,
    modifyRecord1: '',
    data2: [],
    modalVisible2: false,
    modifyRecord2: '',
    data3: [],
    modalVisible3: false,
    modifyRecord3: '',
    data4: [],
    modalVisible4: false,
    modifyRecord4: '',
    userProject: [],
    weekDateEnd: '',
    weekDateStart: '',
    userProjectCode: '',
    fullWeeklyReportData: '',
    momentArray: [],
    departmentList: '',
    newUserInfo: ''
  }

  componentWillMount() {
    this.setState({
      userInfo: JSON.parse(window.localStorage.getItem('userInfo')),
      date: this.getWeek()
    })
    setTimeout(() => {
      this.getUserProject();
      this.getWeeklyDataArray();
      this.getDepartmentList();
      this.getNewUserInfo();
    },0)
  }

  getNewUserInfo = () => {
    Http.request({
      url: '/user/query'
    }).then((resData) => {
      this.setState({
        newUserInfo: resData.data
      })
    })
  }

  getWeek = () => {
    let str = new Date();
    let week = Math.ceil(str.getDate()/7);
    let month = str.getMonth() + 1;
    let year = str.getFullYear();
    if  (str.getDate() < 7) {
        if (str.getDay() !== 1) {
            week = 5;
            month = str.getMonth();
        }
    }
    return {year, month, week}
  }

  closeModal = (type) => {
    this.setState({
      [type]: false
    })
  }

  getDepartmentList = () => {
    Http.request({
      url: '/department/list'
    }).then((redData) => {
      this.setState({
        departmentList: redData.data
      })
    })
  }

  getWeeklyDataArray = () => {
    Http.request({
      url: `/teamReport/query/date/${this.state.date.year}年${this.state.date.month}月第${this.state.date.week}周`
    }).then((resData) => {
      if (resData.data) {
        this.setIndex(resData.data.teamReports);
        this.setIndex(resData.data.teamBuildings);
        this.setIndex(resData.data.teamTrainings);
        this.setIndex(resData.data.teamPatents);
        this.setState({
          fullWeeklyReportData: resData.data,
          momentArray: [moment(new Date(resData.data.start).getTime()), moment(new Date(resData.data.end).getTime())],
          data1: resData.data.teamReports,
          data2: resData.data.teamBuildings,
          data3: resData.data.teamTrainings,
          data4: resData.data.teamPatents
        })
      }
    })
  }

  setIndex = (data) => {
    for (let i = 0; i < data.length; i++) {
      data[i].index = i + 1;
    }
  }

  submitModalData = (data, type) => {
    let url, postData;
    data.key = data.index;
    if (type.type1 === "data1") {
      data.week = `${this.state.date.year}年${this.state.date.month}月第${this.state.date.week}周`;
      data.weekDateEnd = this.state.weekDateEnd;
      data.weekDateStart = this.state.weekDateStart;
      data.projectCode = this.state.userProjectCode;
      data.departmentCode = this.state.userInfo.departCode;
      data.expectDate = moment(data.expectDate).format('YYYY-MM-DD');
      if (this.state[[type.type2]] === '') {
        url = '/teamReport/add';
      } else {
        url = '/teamReport/update';
        data.id = this.state[type.type2].id;
        data.projectCode = this.state.userProjectCode || this.state[type.type2].projectCode;
        data.weekDateEnd = this.state[type.type2].weekDateEnd;
        data.weekDateStart = this.state[type.type2].weekDateStart;
      }
      postData = data;
    } else if (type.type1 === "data2") {
        data.type = "team";
        data.dateMonth = `${this.state.date.year}年${this.state.date.month}月`;
        let item = this.state.departmentList.find((item) => item.name === this.state.userInfo.departName);
        data.code = item.code;
        if (this.state[[type.type2]] === '') {
          url = '/teamBuilding/create';
        } else {
          data.id = this.state[type.type2].id
          url = '/teamBuilding/update';
        }
        postData = data;
    } else if (type.type1 === "data3") {
        data.type = "team";
        data.dateMonth = `${this.state.date.year}年${this.state.date.month}月`;
        let item = this.state.departmentList.find((item) => item.name === this.state.userInfo.departName);
        data.code = item.code;
        data.buildDate = moment(data.buildDate).format('YYYY-MM-DD');
        if (this.state[[type.type2]] === '') {
          url = '/teamTraining/create';
        } else {
          data.id = this.state[type.type2].id
          url = '/teamTraining/update';
        }
        postData = data;
    } else if (type.type1 === "data4") {
        data.dateYear = `${this.state.date.year}`;
        let item = this.state.departmentList.find((item) => item.name === this.state.userInfo.departName);
        data.departCode = item.code;
        if (this.state[[type.type2]] === '') {
          url = '/teamPatents/create';
        } else {
          data.id = this.state[type.type2].id
          url = '/teamPatents/update';
        }
        postData = data;
    }
  
    Http.request({
      url: url,
      method: 'post',
      data: postData
    }).then((resData) => {
      message.success("提交成功");
    })
    this.setState({
      [type.type3]: false,
    })

    setTimeout(() => {
      this.getWeeklyDataArray();
    },500)
  }

  addData = (type) => {
    if (!this.state.weekDateStart) {
      message.warn("请先选择时间段");
      return;
    }
    this.setState({
      [type.type3]: true,
      [type.type2]: ''
    })
    if (this.state[type.type1].length > 0) {
      this.setState({
        [type.type4]: this.state[type.type1][this.state[type.type1].length - 1].index + 1
      })
    }
  }
  modifyItem = (record, type) => {
    if (type.type1 === 'modifyRecord1') {
      record.expectDate = moment(new Date(record.expectDate).getTime());
    } else if (type.type1 === 'modifyRecord3') {
      record.buildDate = moment(new Date(record.buildDate).getTime());
    }
    this.setState({
      [type.type1]: record,
      [type.type2]: true
    })
  }
  deleteItem = (record, type) => {
    let url;
    switch (type) {
      case 'data1':
        url = `/teamReport/delete/${record.id}`
        break;
      case 'data2':
        url = `/teamBuilding/delete/${record.id}`
        break;
      case 'data3':
        url = `/teamTraining/delete/${record.id}`
        break;
      default:
        url = `/teamPatents/delete/${record.id}`
        break;
    }
    Http.request({
      url: url,
      method: 'delete'
    }).then((resData) => {
      message.success('删除成功');
      setTimeout(() => {
        this.getWeeklyDataArray();
      },500)
    })
  }

  getUserProject = () => {
    Http.request({
      url: `/teamReport/projects/${this.state.date.year}年${this.state.date.month}月第${this.state.date.week}周`
    }).then((resData) => {
      this.setState({
        userProject: resData.data
      })
    })
  }

  dateChange = (moment, string) => {
    this.setState({
      weekDateStart: string[0],
      weekDateEnd: string[1]
    })
  }

  userProjectCode = (data) => {
    this.setState({
      userProjectCode: data
    })
  }

  render() {
    const columns1 = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      }, 
      {
        title: '项目名称',
        dataIndex: 'projectName',
        key: 'projectName',
      }, 
      {
        title: '项目成员',
        dataIndex: 'projectMembers',
        key: 'projectMembers',
      }, 
      {
        title: '项目投入人力(人天)',
        dataIndex: 'teamHrTime',
        key: 'teamHrTime',
      }, 
      {
        title: '项目进展(最近一个节点目标)',
        dataIndex: 'projectProgress',
        key: 'projectProgress',
      }, 
      {
        title: '项目是否延期',
        dataIndex: 'projectDelay',
        key: 'projectDelay',
        render: (text, record) => {
          switch (record.projectDelay) {
            case true:
              return '是'
            default:
              return '否'
          }
        }
      },
      {
        title: '项目预期时间',
        dataIndex: 'expectDate',
        key: 'expectDate',
      }, 
      {
        title: '项目目前问题',
        dataIndex: 'problem',
        key: 'problem',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width:150,
        key: 'operation',
        render: (text, record) => (
          <span>
            <a onClick={() => this.modifyItem(record, {type1: 'modifyRecord1', type2: 'modalVisible1'})}>修改</a>
            <span className="ant-divider" />
            <a onClick={() => this.deleteItem(record, 'data1')}>删除</a>
          </span> 
        )
      },
    ];
    const columns2 = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      },
      {
        title: '能力名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '期望效果',
        dataIndex: 'target',
        key: 'target',
      },
      {
        title: '完成情况',
        dataIndex: 'result',
        key: 'result',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width:150,
        key: 'operation',
        render: (text, record) => (
          <span>
            <a onClick={() => this.modifyItem(record, {type1: 'modifyRecord2', type2: 'modalVisible2'})}>修改</a>
            <span className="ant-divider" />
            <a onClick={() => this.deleteItem(record, 'data2')}>删除</a>
          </span> 
        )
      },
    ]
    const columns3 = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      },
      {
        title: '培训内容',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '培训目的',
        dataIndex: 'target',
        key: 'target',
      },
      {
        title: '培训时间',
        dataIndex: 'buildDate',
        key: 'buildDate',
      },
      {
        title: '完成情况',
        dataIndex: 'result',
        key: 'result',
      },
      {
        title: '培训质量-考核成绩',
        dataIndex: 'grade',
        key: 'grade',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width:150,
        key: 'operation',
        render: (text, record) => (
          <span>
            <a onClick={() => this.modifyItem(record, {type1: 'modifyRecord3', type2: 'modalVisible3'})}>修改</a>
            <span className="ant-divider" />
            <a onClick={() => this.deleteItem(record, 'data3')}>删除</a>
          </span> 
        )
      },
    ]
    const columns4 = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      },
      {
        title: '内容',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '目前值',
        dataIndex: 'result',
        key: 'result',
      },
      {
        title: '目标值',
        dataIndex: 'target',
        key: 'target',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width:150,
        key: 'operation',
        render: (text, record) => (
          <span>
            <a onClick={() => this.modifyItem(record, {type1: 'modifyRecord4', type2: 'modalVisible4'})}>修改</a>
            <span className="ant-divider" />
            <a onClick={() => this.deleteItem(record, 'data4')}>删除</a>
          </span> 
        )
      },
    ]
    return (
      <section className="team-weekly">
        <Row gutter={100} className="input-row">
          <Col span={8} className="input-col">
            <span className="lable-span">部门：</span>
            <span>{this.state.newUserInfo.departmentName}</span>
          </Col>
          <Col span={8} className="input-col">
            <span className="lable-span">负责人：</span>
            <span>{this.state.userInfo.name}</span>
          </Col>
          <Col span={8} className="input-col">
            <span className="lable-span">时间：</span>
            <RangePicker onChange={this.dateChange} />
          </Col>
          <Col span={24} className="table-col">
            <Table title={()=> <span className="lable-span">{this.state.date.year}年{this.state.date.month}月第{this.state.date.week}周主要项目汇总-
            <a onClick={() => this.addData({type1: 'data1', type2: 'modifyRecord1', type3: 'modalVisible1', type4: 'index1'})}>添加数据</a></span>} 
            columns={columns1} dataSource={this.state.data1} />
          </Col>
          <Col span={24} className="table-col">
            <Table title={()=> <span className="lable-span">{this.state.date.year}年{this.state.date.month}月月度团队能力建设规划-
            <a onClick={() => this.addData({type1: 'data2', type2: 'modifyRecord2', type3: 'modalVisible2', type4: 'index2'})}>添加数据</a></span>} 
            columns={columns2} dataSource={this.state.data2} />
          </Col>
          <Col span={24} className="table-col">
            <Table title={()=> <span className="lable-span">{this.state.date.year}年{this.state.date.month}月月度团队内部培训汇总-
            <a onClick={() => this.addData({type1: 'data3', type2: 'modifyRecord3', type3: 'modalVisible3', type4: 'index3'})}>添加数据</a></span>} 
            columns={columns3} dataSource={this.state.data3} />
          </Col>
          <Col span={24} className="table-col">
            <Table title={()=> <span className="lable-span">{this.state.date.year}年年度团队专利情况-
            <a onClick={() => this.addData({type1: 'data4', type2: 'modifyRecord4', type3: 'modalVisible4', type4: 'index4'})}>添加数据</a></span>} 
            columns={columns4} dataSource={this.state.data4} />
          </Col>
          <Col span={24} className="table-col button">
            {/* <Button type="primary">提交</Button> */}
            {
              this.props.viewFlag ? <Button type="primary" style={{marginLeft: 20}} onClick={this.props.viewBack}>返回</Button> : ''
            }
          </Col>
        </Row>
        <Modal
          title={this.state.modifyRecord1 === '' ? '添加数据' : '修改数据'}
          width={980}
          wrapClassName="vertical-center-modal"
          visible={this.state.modalVisible1}
          footer={null}
          closable={false}
        >
         {
          this.state.modalVisible1 ? 
          <WeeklyForm1 close={() => this.closeModal('modalVisible1')} submit={this.submitModalData} 
          index={this.state.index1} modifyRecord={this.state.modifyRecord1} userProject={this.state.userProject} userProjectCode={this.userProjectCode}></WeeklyForm1>
          : ""
        }
        </Modal>
        <Modal
          title={this.state.modifyRecord2 === '' ? '添加数据' : '修改数据'}
          width={980}
          wrapClassName="vertical-center-modal"
          visible={this.state.modalVisible2}
          footer={null}
          closable={false}
        >
         {
          this.state.modalVisible2 ? 
          <WeeklyForm2 close={() => this.closeModal('modalVisible2')} submit={this.submitModalData} 
          index={this.state.index2} modifyRecord={this.state.modifyRecord2}></WeeklyForm2>
          : ""
        }
        </Modal>
        <Modal
          title={this.state.modifyRecord3 === '' ? '添加数据' : '修改数据'}
          width={980}
          wrapClassName="vertical-center-modal"
          visible={this.state.modalVisible3}
          footer={null}
          closable={false}
        >
         {
          this.state.modalVisible3 ? 
          <WeeklyForm3 close={() => this.closeModal('modalVisible3')} submit={this.submitModalData} 
          index={this.state.index3} modifyRecord={this.state.modifyRecord3}></WeeklyForm3>
          : ""
        }
        </Modal>
        <Modal
          title={this.state.modifyRecord4 === '' ? '添加数据' : '修改数据'}
          width={980}
          wrapClassName="vertical-center-modal"
          visible={this.state.modalVisible4}
          footer={null}
          closable={false}
        >
         {
          this.state.modalVisible4 ? 
          <WeeklyForm4 close={() => this.closeModal('modalVisible4')} submit={this.submitModalData} 
          index={this.state.index4} modifyRecord={this.state.modifyRecord4}></WeeklyForm4>
          : ""
        }
        </Modal>
      </section>
    )
  }
}
